//
//  MyDocument.m
//  Shopping List
//
//  Created by Tim Isted on 16/09/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MyDocument.h"
#import "ShoppingListItem.h"
#import "PPStrikeThroughCell.h"

@implementation MyDocument

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
	return [shoppingListArray count];
}

- (void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell 
            forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    if( tableColumn != itemNameColumn ) return;
    
    ShoppingListItem *currentItem = [shoppingListArray objectAtIndex:row];
    if( [currentItem purchased] )
        [cell setShouldDrawLine:YES];
    else
        [cell setShouldDrawLine:NO];
}


- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	ShoppingListItem *currentItem = [shoppingListArray objectAtIndex:rowIndex]; 
	
	if( aTableColumn == quantityColumn )
		return [NSNumber numberWithInt:[currentItem quantity]];
	else if( aTableColumn == itemNameColumn )
		return [currentItem itemName];
    else if( aTableColumn == purchasedColumn ) 
        return [NSNumber numberWithBool:[currentItem purchased]];
	else 
		return nil;
}

- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	ShoppingListItem *currentItem = [shoppingListArray objectAtIndex:rowIndex]; 
	
	if( aTableColumn == quantityColumn )
		[currentItem setQuantity:[anObject intValue]];
	else if( aTableColumn == itemNameColumn )
		[currentItem setItemName:anObject];
    else if( aTableColumn == purchasedColumn ) {
        [currentItem setPurchased:[anObject boolValue]];
        
        NSIndexSet *rowIndexSet = [NSIndexSet indexSetWithIndex:rowIndex];
        
        NSArray *columnsArray = [shoppingListTableView tableColumns];
        NSInteger columnIndex = [columnsArray indexOfObject:itemNameColumn];
        NSIndexSet *columnIndexSet = [NSIndexSet indexSetWithIndex:columnIndex];
        
        [shoppingListTableView reloadDataForRowIndexes:rowIndexSet columnIndexes:columnIndexSet];
    }
    
    //[self updateChangeCount:NSChangeDone];
}

- (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
    
    // we're only interested in validating the removeItem... action
    if ([menuItem action] == @selector(removeItemFromShoppingList:)) {
        NSIndexSet *rowIndexes = [shoppingListTableView selectedRowIndexes];
        
        if( [rowIndexes count] > 0 )
            return YES; // enable if there's a selection
        else
            return NO; // otherwise disable
    }
    
    return [super validateMenuItem:menuItem];
}

- (IBAction)addNewItemToShoppingList:(id)sender
{
	ShoppingListItem *newItem = [ShoppingListItem 
				 shoppingListItemWithName:[newItemNameTextField stringValue]
								 quantity:[newItemQuantityTextField intValue]];
	
	[shoppingListArray addObject:newItem];
	
	[shoppingListTableView reloadData];
	
	if( sender == newItemNameTextField || sender == newItemQuantityTextField ) {
		[newItemNameTextField setStringValue:@""];
		[newItemQuantityTextField setStringValue:@"1"];
		[[newItemNameTextField window] makeFirstResponder:newItemNameTextField];
	}
    
    //[self updateChangeCount:NSChangeDone];
}

- (IBAction)removeItemFromShoppingList:(id)sender
{
	int selectedItemIndex = [shoppingListTableView selectedRow];
	if( selectedItemIndex == -1 ) return;
	
	NSAlert *alert = [[NSAlert alloc] init]; 
	[alert addButtonWithTitle:@"Delete"]; 
	[alert addButtonWithTitle:@"Cancel"]; 
	[alert setMessageText:@"Delete the shopping list item?"]; 
	[alert setInformativeText:@"Deleted items cannot be restored."]; 
	[alert setAlertStyle:NSWarningAlertStyle];
	
	int returnValue = [alert runModal]; 
	
	if( returnValue == NSAlertFirstButtonReturn )
	{
		[shoppingListArray removeObjectAtIndex:selectedItemIndex];
		[shoppingListTableView reloadData];
        
        //[self updateChangeCount:NSChangeDone];
	}
	
	[alert release];
}

- (id)init
{
    self = [super init];
    if (self) {
		// Create the main shopping list array
        shoppingListArray = [[NSMutableArray alloc] 
							 init];
		
		// Add the Milk
		ShoppingListItem *milkItem = [ShoppingListItem shoppingListItemWithName:@"Milk" quantity:4];
		[shoppingListArray addObject:milkItem];
		
		// Add the Eggs
		ShoppingListItem *eggsItem = [ShoppingListItem shoppingListItemWithName:@"Eggs" quantity:12];
		[shoppingListArray addObject:eggsItem];
		
		// Add the Butter
		ShoppingListItem *butterItem = [ShoppingListItem shoppingListItemWithName:@"Butter" quantity:1];
		[shoppingListArray addObject:butterItem];
    }
    return self;
}

- (void)dealloc
{
	[shoppingListArray release]; 
	
	[super dealloc];
}

- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    [super windowControllerDidLoadNib:aController];
    // Add any code here that needs to be executed once the windowController has loaded the document's window.
}

- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{
	return [NSKeyedArchiver archiveRootObject:shoppingListArray toFile:[absoluteURL path]]; 
    //return [shoppingListArray writeToURL:absoluteURL atomically:YES];
}

- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{
	[shoppingListArray release];
    
    NSArray *restoredList = [NSKeyedUnarchiver unarchiveObjectWithFile:[absoluteURL path]];
    if( !restoredList ) return NO; // couldn't open the file
    
    shoppingListArray = [restoredList retain];
	[shoppingListTableView reloadData];
	
	return YES;
}

@end
